<template>
  <div>
    <!-- drawer绑定用户 -->
    <el-drawer
      :title="dialogAttr.title"
      :visible.sync="isOpen"
      direction="rtl"
      size="50%"
      append-to-body
      :before-close="handleClose"
    >
      <el-form :model="bindUserQuery" ref="bindUserQueryForm" size="medium" :inline="true">
        <el-form-item>
          <el-button plain class="bindBtn" type="primary" @click="handleUnBindUserList">绑定用户</el-button>
        </el-form-item>
        <el-form-item prop="name">
          <el-input v-model="bindUserQuery.name" placeholder="请输入用户姓名" clearable />
        </el-form-item>
        <el-form-item prop="deptId">
          <treeselect
            v-model="bindUserQuery.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="请选择归属部门"
            class="treeselect_main"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="medium"
            @click="handleQueryBindUser"
          >搜索</el-button>
          <el-button icon="el-icon-refresh" size="medium" @click="resetBindUserQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="16" class="drawer_el_row">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteBindUser"
          >解绑</el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionBindUserChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名" align="center" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="姓名" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
        <el-table-column
          label="手机号码"
          align="center"
          prop="phonenumber"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUserRemove(scope.row)"
            >解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="bindUserQuery.total>0"
        :total="bindUserQuery.total"
        :page.sync="bindUserQuery.pageNum"
        :limit.sync="bindUserQuery.pageSize"
        @pagination="getUserList"
      />
    </el-drawer>
  </div>
</template>

<script>
// 已绑定用户列表
import { listSimpleDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "BindUserList",
  dicts: ["sys_user_sex"],
  components: {
    Treeselect
  },
  props: {
    bindId: {
      type: Object,
      default: () => {
        return {
          type: "str",
          value: 0
        };
      }
    },
    // 已绑定用户列表
    getBindUserList: {
      type: Function,
      default: () => {}
    },
    // 解绑用户
    removeBindUser: {
      type: Function,
      default: () => {}
    },
    // 弹框属性
    dialogAttr: {
      type: Object,
      default: () => {
        return {
          title: "",
          show: false
        };
      }
    }
  },
  data() {
    return {
      // 部门树选项
      deptOptions: [],
      // 绑定用户查询
      bindUserQuery: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        name: undefined,
        total: 0
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 加载
      loading: false,
      // 用户列表
      userList: [],
      // 是否含有中间表id
      hasId: false
    };
  },
  methods: {
    /** 获取简易部门列表 */
    getListSimpleDept() {
      listSimpleDept()
        .then(res => {
          this.deptOptions = this.handleTree(res.data, "deptId");
        })
        .finally(() => {});
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    getUserList() {
      this.loading = true;
      this.getBindUserList(this.bindUserQuery)
        .then(res => {
          this.userList = res.rows;
          this.bindUserQuery.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 解绑用户 */
    handleUserRemove(row) {
      let data;
      if (row.id == null || row.id == undefined) {
        let key = this.bindId.type;
        let value = this.bindId.value;
        data = {
          userId: row.userId
        };
        data[key] = value;
        data = [data];
        // 不含中间表id数据
        this.hasId = false;
      } else {
        data = { ids: [row.id] };
        this.hasId = true;
      }
      this.removeBindUser(data)
        .then(res => {
          this.$modal.msgSuccess("解绑成功");
          this.getUserList();
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索已绑定用户 */
    handleQueryBindUser() {
      this.bindUserQuery.pageNum = 1;
      this.getUserList();
    },
    resetBindUserQuery() {
      this.resetForm("bindUserQueryForm");
      this.bindUserQuery.deptId = undefined;
      this.handleQueryBindUser();
    },
    /** 批量解绑 */
    handleSelectionBindUserChange(data) {
      let datas = data.map(item => {
        if (!this.hasId) {
          let key = this.bindId.type;
          let value = this.bindId.value;
          let formatData = {
            userId: item.userId
          };
          formatData[key] = value;
          return formatData;
        } else {
          return item.id;
        }
      });
      this.single = data.length !== 1;
      this.multiple = !data.length;
      this.bindUserDelList = datas;
    },
    handleDeleteBindUser() {
      let datas = this.bindUserDelList;
      if (datas.length > 0) {
        this.$modal
          .confirm("是否解除绑定这" + datas.length + "个用户？")
          .then(() => {
            this.loading = true;
            this.removeBindUser(this.hasId ? { ids: datas } : datas)
              .then(() => {
                this.$modal.msgSuccess("解绑成功");
                this.getUserList();
              })
              .finally(() => {
                this.loading = false;
              });
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    handleUnBindUserList() {
      // 绑定用户弹框
      this.$emit("openUnBindList");
    },

    /** 关闭时的回调 */
    handleClose() {
      this.bindId.value = 0;
      this.dialogAttr.show = false;
    }
  },
  computed: {
    /** 弹框是否打开 */
    isOpen: {
      get() {
        return this.dialogAttr.show;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    }
  },
  watch: {
    bindId: {
      handler(val) {
        if (val.value != 0 && val.value != "0") {
          let idType = val.type;
          this.bindUserQuery[idType] = val.value;
          this.getUserList();
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getListSimpleDept();
  }
};
</script>

<style scoped>
.bindBtn {
  margin-left: 10px;
}

.treeselect_main {
  width: 200px;
  height: 36px;
}
.drawer_el_row {
  margin: 0 !important;
  margin-bottom: 10px !important;
}
</style>